package com.xwd.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xwd.constants.AjaxResult;
import com.xwd.constants.BeanListCopyUtils;
import com.xwd.domain.dto.BookDto;
import com.xwd.domain.vo.BookVO;
import com.xwd.service.BookService;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    //logger
    static Logger logger = Logger.getLogger(BookController.class);

    //controller调用service层
    @Autowired
    @Qualifier("bookService")
    private BookService service;


    //methods
    //查询所有的书籍
    @GetMapping(value = "/get/list")
    @ResponseBody
    public AjaxResult selectAllBook() {
        List<BookDto> bookDtos = service.queryAllBook();
        List<BookVO> bookVOS = BeanListCopyUtils.copyListBeanProperties(bookDtos, BookVO::new);
        logger.info(bookVOS);
        return AjaxResult.success(bookVOS);
    }

    //通过实体属性查询对应的书籍
    @PostMapping(value = "/post/list")
    @ResponseBody
    public AjaxResult selectBooks(@RequestBody BookDto bookDto){
        System.out.println(bookDto);
        List<BookDto> bookDtos = service.queryBooktByWhere(bookDto);
        List<BookVO> bookVOS = BeanListCopyUtils.copyListBeanProperties(bookDtos, BookVO::new);
        logger.info(bookVOS);
        return AjaxResult.success(bookVOS);
    }

    @PutMapping(value = "/update/book")
    @ResponseBody
    public AjaxResult updateBook(@RequestBody @Valid BookDto bookDto){
        System.out.println("更新操作"+bookDto.toString());
        int rows = service.updateBookByID(bookDto);
        System.out.println("更新之后的结果:"+bookDto);
        return rows!=0?AjaxResult.success("更新成功",bookDto):AjaxResult.error("更新失败");
    }

    @DeleteMapping(value = "/delete/book")
    @ResponseBody
    public AjaxResult deleteBook(@NotNull @RequestParam("bookID")Integer bookID){
        int rows = service.deleteBookByID(bookID);
        return rows!=0?AjaxResult.success("删除成功",bookID):AjaxResult.error("删除失败");
    }

}
